package com.ucar.common.utils.page.jpa;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import com.ucar.common.utils.page.jpa.model.OrderingConditions;
import com.ucar.common.utils.page.jpa.model.PagingConditions;

/**
 * 将传入的分页条件
 * @author dinghao
 *
 */
public class PagingUtil {
	
    private PagingUtil() {};

    /**
     * 将paging对象转换为jpa查询参数pageable
     * 
     * @param pagingConditions 分页条件
     * @return Pageable对象 jpa分页查询的一个参数    carDao.findAll(Criteria, PagingUtils.getPageable(paging))
     * 
     */
    public static Pageable getPageable(PagingConditions pagingConditions) {
    	
        PageRequest pageRequest;
        //获取分页条件中的排序条件（包括正序和倒叙，以及按属性排序）
        List<OrderingConditions> orderingConditions = pagingConditions.getSort();
        
        List<Order> orders = new ArrayList<Order>();
        
        if (null != orderingConditions && !orderingConditions.isEmpty()) {
            for (OrderingConditions ordering : orderingConditions) {
                Order order = parseToOrder(ordering);
                orders.add(order);
            }
            Sort sort = new Sort(orders);
            pageRequest = new PageRequest(pagingConditions.getPageIndex(), pagingConditions.getPageSize(), sort);
        } else {
            pageRequest = new PageRequest(pagingConditions.getPageIndex(), pagingConditions.getPageSize());
        }
        return pageRequest;
    }

    /**
     * 将OrderingConditions model对象解析为Order对象
     * @param orderingConditions
     * @return
     */
    private static Order parseToOrder(OrderingConditions orderingConditions) {
        Order order = null;
        String direction = orderingConditions.getDirection();

        if (null != direction) {
            if ("desc".equals(direction.toLowerCase())) {
                order = new Order(Direction.DESC, orderingConditions.getField());
            } else {
                order = new Order(Direction.ASC, orderingConditions.getField());
            }
        } else {
            order = new Order(orderingConditions.getField());
        }
        return order;
    }
}
